package com.by.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${auth.key}")
    String key;

    @Value("${auth.secret}")
    String secret;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String auth = request.getHeader("Authorization");
        if (null == auth) {
            //没有认证信息 直接返回
            resp(response, "{\"code\":0,\"msg\":\"没有授权!\"}");
            return false;
        }
        //有验证值的格式  "Basic " + base64Encode((username + ":" + password).getBytes(charset));
        String[] tmp = auth.split("\\s+");
        //获取用户名和密码
        String userpwd = new String(Base64Utils.decode(tmp[1].getBytes()));
        //分隔用户名和密码
        tmp = userpwd.split(":");
        String username = tmp[0];
        String password = tmp[1];

        if (key.equals(username) && secret.equals(password)) {
            //正确 放行
            return true;
        }

        resp(response, "{\"code\":0, \"msg\":\"授权信息不正确!\"}");
        return false;

    }

    void resp(HttpServletResponse response, String msg) {
        //设置响应内容的类型和编码
        response.setContentType("application/json;charset=utf-8");
        //获取响应输出流
        try (PrintWriter pw = response.getWriter();) {
            //输出
            pw.write(msg);
        } catch (IOException e) {

        }
    }
}
